<template>
  <div class="contract-edit-container">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <div>
          <h2>编辑合同</h2>
          <div class="breadcrumb">
            <router-link to="/contracts">合同管理</router-link> >
            <router-link :to="`/contracts/${contractId}`">合同详情</router-link> >
            编辑合同
          </div>
        </div>
        <div class="d-flex gap-2">
          <button @click="goToEmployeeDashboard" class="btn btn-secondary">
            <i class="fa fa-home mr-2"></i>返回主页
          </button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
    </div>

    <!-- 合同基本信息 -->
    <div v-if="contract && !loading" class="card">
      <div class="card-body">
        <h3 class="contract-name">{{ contract.name }}</h3>
        <div class="contract-info">
          <p><strong>客户:</strong> {{ contract.customer?.companyName || '未选择' }}</p>
          <p><strong>项目经理:</strong> {{ projectManagerName }}</p>
          <p><strong>状态:</strong>
            <span :class="`status-tag status-${contract.status.toLowerCase()}`">
              {{ getStatusChineseName(contract.status) }}
            </span>
          </p>
          <p><strong>创建时间:</strong> {{ formatDate(contract.createTime) }}</p>
        </div>
      </div>
    </div>

    <!-- 条款管理区域 -->
    <div v-if="contractId && !loading" class="card mt-4">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h3>条款管理</h3>
        <span class="badge bg-secondary">{{ clauses.length }} 条条款</span>
      </div>
      <div class="card-body">
        <div v-if="clauses.length > 0" class="clauses-list">
          <ul class="list-group">
            <li
                v-for="clause in clauses"
                :key="clause.id"
                class="list-group-item d-flex flex-column"
            >
              <div class="d-flex justify-content-between align-items-start w-100">
                <div class="flex-grow-1">
                  <p class="mb-1"><strong>条款ID:</strong> {{ clause.id }}</p>
                  <p class="mb-1"><strong>内容:</strong> {{ clause.content }}</p>
                  <p class="mb-0"><strong>累计引用次数:</strong> {{ clause.usageCount }}</p>
                </div>
                <div class="btn-group flex-row gap-2" role="group">
                  <button
                      @click="viewClauseDetail(clause.id)"
                      class="btn btn-info btn-sm"
                      title="查看条款详情"
                  >
                    <i class="fa fa-eye mr-1"></i>查看详情
                  </button>
                  <button
                      @click="removeClause(clause.id)"
                      class="btn btn-danger btn-sm"
                      title="删除条款"
                  >
                    <i class="fa fa-trash mr-1"></i>删除
                  </button>
                </div>
              </div>
              <div class="mt-2 pt-2 border-top"></div>
            </li>
          </ul>
        </div>
        <div v-else class="empty-message text-center py-4">
          <i class="fa fa-info-circle text-muted mr-2"></i>还没有添加条款
        </div>

        <div class="button-group mt-4 d-flex justify-content-end gap-2">
          <button @click="openAIAssistant" class="btn btn-primary">
            <i class="fa fa-robot mr-2"></i>AI助手
          </button>
          <button
              @click="createNewClause"
              class="btn btn-success"
          >
            <i class="fa fa-plus mr-2"></i>创建新条款
          </button>
          <button
              @click="openClauseSelectModal"
              class="btn btn-primary"
          >
            <i class="fa fa-list mr-2"></i>选择已有条款
          </button>
        </div>
      </div>
    </div>

    <!-- 条款选择模态框 -->
    <transition name="modal-fade">
      <div v-if="isClauseSelectModalOpen" class="modal-backdrop" @click.self="closeClauseSelectModal">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h3 class="modal-title">选择已有条款（按引用次数排序）</h3>
              <button type="button" class="close" @click="closeClauseSelectModal">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <div v-if="isLoadingClauses" class="loading-indicator">
                <div class="spinner"></div>
                <p>加载条款中...</p>
              </div>

              <div v-if="clauseSelectError" class="error-message">
                <i class="fa fa-exclamation-circle mr-2"></i>{{ clauseSelectError }}
              </div>

              <!-- 条款列表：仅第一页前10条显示排名 -->
              <div v-if="!isLoadingClauses && availableClauses.length > 0" class="clause-select-list">
                <ul class="list-group clause-separated-list">
                  <li
                      v-for="(clause, index) in availableClauses"
                      :key="clause.id"
                      class="list-group-item d-flex justify-content-between align-items-start"
                      :class="{ 'no-bottom-border': index === availableClauses.length - 1 }"
                  >
                    <div class="clause-info-container flex-grow-1">
                      <div class="clause-content-row d-flex justify-content-between align-items-start">
                        <!-- 排名 + 条款内容：仅第一页(index < 10)显示排名 -->
                        <div class="d-flex">
                          <!-- 核心修改：添加currentPage === 0判断，仅第一页显示排名 -->
                          <span
                              v-if="currentPage === 0 && index < 10"
                              class="rank-badge"
                              :class="getRankClass(index)"
                          >
                            {{ index + 1 }}
                          </span>
                          <span class="clause-content">{{ clause.content }}</span>
                        </div>
                        <!-- 选择按钮 -->
                        <button
                            @click="selectClause(clause.id)"
                            class="btn btn-primary btn-sm ml-2 align-self-start"
                            title="选择此条款"
                        >
                          <i class="fa fa-check mr-1"></i>选择
                        </button>
                      </div>
                      <!-- ID和引用次数 -->
                      <div class="clause-meta mt-1">
                        <span class="meta-item">ID: {{ clause.id }}</span>
                        <span class="meta-item usage-count">引用次数: {{ clause.usageCount }}</span>
                      </div>
                    </div>
                  </li>
                </ul>
              </div>

              <div v-else-if="!isLoadingClauses && availableClauses.length === 0" class="empty-message text-center py-4">
                <i class="fa fa-info-circle text-muted mr-2"></i>没有可用的条款
              </div>

              <div v-if="!isLoadingClauses && availableClauses.length > 0" class="pagination mt-3">
                <button
                    @click="prevPage"
                    :disabled="currentPage === 0"
                    class="btn btn-sm btn-secondary"
                >
                  上一页
                </button>
                <span class="mx-2">
                  第 {{ currentPage + 1 }} 页，共 {{ totalPages }} 页
                </span>
                <button
                    @click="nextPage"
                    :disabled="currentPage === totalPages - 1"
                    class="btn btn-sm btn-secondary"
                >
                  下一页
                </button>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" @click="closeClauseSelectModal">
                关闭
              </button>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <!-- AI助手对话模态框 -->
    <transition name="modal-fade">
      <div v-if="aiAssistantVisible" class="modal-backdrop" @click.self="closeAIAssistant">
        <div class="modal-dialog ai-modal" role="document">
          <div class="modal-content ai-content">
            <div class="modal-header ai-header">
              <h3 class="modal-title">合同助手</h3>
              <button type="button" class="close" @click="closeAIAssistant">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body ai-body">
              <div class="chat-messages" ref="chatContainer">
                <div v-for="(msg, index) in chatHistory" :key="index" class="message" :class="msg.type">
                  <div class="avatar" :class="msg.type">{{ msg.type === 'user' ? '👤' : '🤖' }}</div>
                  <div class="message-content">
                    <div v-if="msg.type === 'assistant' && msg.thinking" class="thinking-process">
                      <span class="thinking-label">思考过程：</span>
                      <p>{{ msg.thinking }}</p>
                    </div>
                    <div class="answer-content">
                      <p>{{ msg.answer || msg.content }}</p>
                    </div>
                  </div>
                </div>
              </div>

              <div class="chat-input">
                <textarea
                    v-model="aiQuery"
                    placeholder="问我关于合同的问题..."
                    @keyup.enter="sendAIQuery"
                    :disabled="aiLoading"
                ></textarea>
                <button @click="sendAIQuery" class="send-btn" :disabled="aiLoading">
                  <i class="fa fa-paper-plane"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ContractEdit',
  data() {
    return {
      contractId: null,
      contract: null,
      clauses: [],
      errorMessage: '',
      loading: true,
      aiAssistantVisible: false,
      aiQuery: '',
      chatHistory: [],
      aiLoading: false,

      // 条款选择模态框相关
      isClauseSelectModalOpen: false,
      availableClauses: [],
      isLoadingClauses: false,
      clauseSelectError: '',
      currentPage: 0,  // 当前页码（0为第一页）
      totalPages: 0,
      pageSize: 10,

      // 合同状态映射表
      statusMap: {
        DRAFT: "草稿",
        PENDING_REVIEW: "待审核",
        REVIEW_FAILED: "审核失败",
        PENDING_CONFIRMATION: "待确认",
        CONFIRMED: "已确认",
        COMPLETED: "已完成",
        ARCHIVED: "已归档"
      }
    }
  },
  computed: {
    projectManagerName() {
      return this.contract?.projectManager?.name || '未指定'
    }
  },
  created() {
    this.contractId = this.$route.params.contractId
    this.fetchContractDetails()
    this.fetchClauses()
  },
  methods: {
    // 获取排名样式（前10条不同颜色）
    getRankClass(index) {
      const rank = index + 1
      if (rank === 1) return 'rank-1'
      if (rank === 2) return 'rank-2'
      if (rank === 3) return 'rank-3'
      return 'rank-top10'
    },

    parseAIResponse(responseText) {
      const separator = '<think>'
      const parts = responseText.split(separator)
      if (parts.length < 3) {
        return {
          thinking: '（未获取到思考过程）',
          answer: responseText.trim() || '（无有效回答内容）'
        }
      }
      return {
        thinking: parts[1].trim() || '（无思考过程）',
        answer: parts[2].trim() || '（无有效回答内容）'
      }
    },

    getStatusChineseName(statusKey) {
      return this.statusMap[statusKey] || statusKey
    },

    openAIAssistant() {
      this.aiAssistantVisible = true
      this.chatHistory = [
        { type: 'assistant', content: '你好！我是合同助手，有什么可以帮你的？' }
      ]
    },

    closeAIAssistant() {
      this.aiAssistantVisible = false
      this.aiQuery = ''
    },

    sendAIQuery() {
      const query = this.aiQuery.trim()
      if (!query) return

      this.chatHistory.push({ type: 'user', content: query })
      this.aiQuery = ''
      this.aiLoading = true

      this.chatHistory.push({ type: 'assistant', content: '正在生成回答，请稍候...' })
      this.scrollToBottom()

      axios.post('/auth/ai/query', {
        query,
        contractId: this.contractId
      })
          .then(response => {
            this.chatHistory.pop()
            const aiResponse = this.parseAIResponse(response.data.answer || '')
            this.chatHistory.push({
              type: 'assistant',
              thinking: aiResponse.thinking,
              answer: aiResponse.answer
            })
          })
          .catch(error => {
            this.chatHistory.pop()
            console.error('AI查询失败:', error)
            this.chatHistory.push({
              type: 'assistant',
              content: '抱歉，查询失败，请稍后再试。'
            })
          })
          .finally(() => {
            this.aiLoading = false
            this.scrollToBottom()
          })
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const chatContainer = this.$refs.chatContainer
        if (chatContainer) {
          chatContainer.scrollTop = chatContainer.scrollHeight
        }
      })
    },

    goToEmployeeDashboard() {
      this.$router.push('/employee/dashboard')
    },

    fetchContractDetails() {
      if (!this.contractId) {
        this.errorMessage = '缺少合同ID参数'
        setTimeout(() => this.$router.push('/contracts'), 2000)
        return
      }

      axios.get(`/auth/contracts/${this.contractId}`)
          .then(response => {
            this.contract = response.data
          })
          .catch(err => {
            console.error('获取合同详情失败:', err)
            this.errorMessage = '获取合同详情失败，请重试'
          })
          .finally(() => {
            this.loading = false
          })
    },

    fetchClauses() {
      if (!this.contractId) return

      axios.get(`/auth/clauses/contract/${this.contractId}`)
          .then(response => {
            this.clauses = response.data
          })
          .catch(err => {
            console.error('获取合同条款失败:', err)
            this.errorMessage = '获取合同条款失败，请重试'
          })
    },

    viewClauseDetail(clauseId) {
      this.$router.push({
        name: 'ClauseDetail',
        params: { contractId: this.contractId, clauseId: clauseId }
      })
    },

    createNewClause() {
      this.$router.push({
        name: 'ClauseCreate',
        params: { contractId: this.contractId }
      })
    },

    removeClause(clauseId) {
      if (!confirm('确定要删除这个条款吗？删除后无法恢复')) return

      axios.delete(`/auth/clauses/${clauseId}/contract/${this.contractId}`)
          .then(() => {
            this.fetchClauses()
            alert('条款删除成功')
          })
          .catch(err => {
            console.error('删除条款失败:', err)
            this.errorMessage = '删除条款失败，请重试'
          })
    },

    openClauseSelectModal() {
      if (!this.contractId) {
        this.errorMessage = '请先选择合同，再选择已有条款'
        return
      }

      this.isClauseSelectModalOpen = true
      this.isLoadingClauses = true
      this.clauseSelectError = ''
      this.currentPage = 0  // 打开时默认显示第一页
      this.fetchAvailableClauses()
    },

    // 获取可用条款：按引用次数排序
    fetchAvailableClauses() {
      axios.get(`/auth/clauses/available/${this.contractId}`, {
        params: { page: this.currentPage, size: this.pageSize }
      })
          .then(response => {
            const clauses = response.data.content || []
            this.availableClauses = clauses.sort((a, b) => b.usageCount - a.usageCount)
            this.totalPages = response.data.totalPages
            this.currentPage = response.data.currentPage
          })
          .catch(err => {
            console.error('获取可用条款失败:', err)
            this.clauseSelectError = '获取条款失败，请重试'
          })
          .finally(() => {
            this.isLoadingClauses = false
          })
    },

    closeClauseSelectModal() {
      this.isClauseSelectModalOpen = false
    },

    selectClause(clauseId) {
      axios.post('/auth/clauses/associate', {
        contractId: this.contractId,
        clauseId: clauseId
      })
          .then(() => {
            this.fetchClauses()
            this.closeClauseSelectModal()
            alert('条款已添加到合同')
          })
          .catch(err => {
            console.error('关联条款失败:', err)
            this.clauseSelectError = err.response?.data?.message || '添加条款失败，请重试'
          })
    },

    prevPage() {
      if (this.currentPage > 0) {
        this.currentPage--
        this.fetchAvailableClauses()
      }
    },

    nextPage() {
      if (this.currentPage < this.totalPages - 1) {
        this.currentPage++
        this.fetchAvailableClauses()
      }
    },

    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString()
    }
  }
}
</script>

<style scoped>
/* 排名样式 */
.rank-badge {
  display: inline-block;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  color: white;
  text-align: center;
  line-height: 24px;
  font-weight: bold;
  margin-right: 8px;
  font-size: 0.8em;
}

.rank-1 { background-color: #ffc107; }
.rank-2 { background-color: #6c757d; }
.rank-3 { background-color: #fd7e14; }
.rank-top10 { background-color: #28a745; }

/* 条款分隔样式 */
.clause-separated-list .list-group-item {
  border-bottom: 1px dashed #e9ecef;
  padding: 15px 20px;
  margin-bottom: 5px;
}

.no-bottom-border {
  border-bottom: none !important;
  margin-bottom: 0 !important;
}

/* 条款信息布局 */
.clause-info-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.clause-content-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
}

.clause-content {
  word-break: break-all;
  margin-bottom: 4px;
  flex-grow: 1;
  padding-right: 10px;
}

.clause-meta {
  display: flex;
  gap: 12px;
  font-size: 0.9em;
  color: #6c757d;
  margin-top: 4px;
}

.usage-count {
  color: #007bff;
  font-weight: 500;
}

/* AI思考过程样式 */
.thinking-process {
  font-size: 0.9em;
  color: #6c757d;
  background-color: #f8f9fa;
  padding: 8px 12px;
  border-radius: 6px;
  margin-bottom: 10px;
  border-left: 3px solid #007bff;
}

.thinking-label {
  font-weight: 600;
  color: #007bff;
}

/* 基础样式（保持不变） */
.contract-edit-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.9em;
  font-weight: 500;
}

.status-draft { background-color: #e9ecef; color: #495057; }
.status-pending_review { background-color: #fff3cd; color: #856404; }
.status-review_failed { background-color: #f8d7da; color: #721c24; }
.status-pending_confirmation { background-color: #d1ecf1; color: #0c5460; }
.status-confirmed { background-color: #d4edda; color: #155724; }
.status-completed { background-color: #c3e6cb; color: #155724; }
.status-archived { background-color: #f3f4f6; color: #4a5568; }

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  min-height: 300px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #007bff;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin { to { transform: rotate(360deg); } }

.error-message {
  color: #721c24;
  background-color: #f8d7da;
  border-left: 4px solid #f5c6cb;
  padding: 12px 15px;
  border-radius: 0 4px 4px 0;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.card {
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.card:hover { box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1); }

.card-header {
  background-color: #f8f9fa;
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-body { padding: 20px; }

.btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0069d9;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 123, 255, 0.2);
}

/* 模态框样式 */
.modal-backdrop {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  overflow-y: auto;
}

.modal-dialog {
  max-width: 700px;
  width: 90%;
  margin: 1.75rem auto;
}

.modal-content {
  background-color: white;
  border-radius: 0.3rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  position: relative;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.modal-body {
  padding: 20px;
  position: relative;
  flex: 1 1 auto;
  max-height: 60vh;
  overflow-y: auto;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 其他样式保持不变 */
</style>

<style scoped>
/* 新增：条款分隔样式 */
.clause-separated-list .list-group-item {
  border-bottom: 1px dashed #e9ecef; /* 虚线分隔 */
  padding: 15px 20px; /* 增加内边距，增强分隔感 */
  margin-bottom: 5px; /* 增加底部间距 */
}

/* 最后一条条款移除底部边框 */
.no-bottom-border {
  border-bottom: none !important;
  margin-bottom: 0 !important;
}

/* 排名样式 */
.rank-badge {
  display: inline-block;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  color: white;
  text-align: center;
  line-height: 24px;
  font-weight: bold;
  margin-right: 8px;
  font-size: 0.8em;
}

.rank-1 {
  background-color: #ffc107; /* 金色 */
}
.rank-2 {
  background-color: #6c757d; /* 银色 */
}
.rank-3 {
  background-color: #fd7e14; /* 铜色 */
}
.rank-top10 {
  background-color: #28a745; /* 绿色 */
}

/* 条款信息布局调整 */
.clause-info-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.clause-content-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
}

.clause-content {
  word-break: break-all;
  margin-bottom: 4px;
  flex-grow: 1;
  padding-right: 10px;
}

.clause-meta {
  display: flex;
  gap: 12px;
  font-size: 0.9em;
  color: #6c757d;
  margin-top: 4px;
}

.meta-item {
  display: inline-block;
}

/* 引用次数高亮 */
.usage-count {
  color: #007bff;
  font-weight: 500;
}

/* AI思考过程与回答的显示样式 */
.thinking-process {
  font-size: 0.9em;
  color: #6c757d;
  background-color: #f8f9fa;
  padding: 8px 12px;
  border-radius: 6px;
  margin-bottom: 10px;
  border-left: 3px solid #007bff;
}

.thinking-label {
  font-weight: 600;
  color: #007bff;
}

.answer-content {
  line-height: 1.6;
}

/* AI输入框加载状态 */
.chat-input textarea:disabled,
.send-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.contract-edit-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

/* 状态标签样式（不同状态显示不同颜色） */
.status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.9em;
  font-weight: 500;
}

.status-draft {
  background-color: #e9ecef;
  color: #495057;
}
.status-pending_review {
  background-color: #fff3cd;
  color: #856404;
}
.status-review_failed {
  background-color: #f8d7da;
  color: #721c24;
}
.status-pending_confirmation {
  background-color: #d1ecf1;
  color: #0c5460;
}
.status-confirmed {
  background-color: #d4edda;
  color: #155724;
}
.status-completed {
  background-color: #c3e6cb;
  color: #155724;
}
.status-archived {
  background-color: #f3f4f6;
  color: #4a5568;
}

.btn-group .btn-sm {
  padding: 5px 10px;
  white-space: nowrap;
}

.flex-row {
  display: flex;
  flex-direction: row;
}

.header {
  margin-bottom: 30px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.breadcrumb {
  font-size: 0.9rem;
  color: #6c757d;
  margin-top: 10px;
}

.breadcrumb router-link {
  color: #007bff;
  text-decoration: none;
}

.breadcrumb router-link:hover {
  text-decoration: underline;
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  min-height: 300px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #007bff;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  color: #721c24;
  background-color: #f8d7da;
  border-left: 4px solid #f5c6cb;
  padding: 12px 15px;
  border-radius: 0 4px 4px 0;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.card {
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.card:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.card-header {
  background-color: #f8f9fa;
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-body {
  padding: 20px;
}

.contract-name {
  margin-bottom: 20px;
  font-size: 1.5rem;
  color: #333;
}

.contract-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.contract-info p {
  margin: 5px 0;
  flex: 1 1 300px;
}

.btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0069d9;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 123, 255, 0.2);
}

.btn-success {
  background-color: #28a745;
  color: white;
}

.btn-success:hover {
  background-color: #218838;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(40, 167, 69, 0.2);
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-danger:hover {
  background-color: #c82333;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(220, 53, 69, 0.2);
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #5a6268;
}

.button-group {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: flex-end;
}

.clauses-list {
  margin-bottom: 20px;
}

.badge {
  font-size: 0.75rem;
  padding: 4px 8px;
}

.empty-message {
  color: #6c757d;
  font-style: italic;
  padding: 30px 0;
  text-align: center;
  border: 1px dashed #dee2e6;
  border-radius: 4px;
}

/* 模态框样式 */
.modal-backdrop {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  overflow-y: auto;
}

.modal-dialog {
  max-width: 700px;
  width: 90%;
  margin: 1.75rem auto;
}

.modal-content {
  background-color: white;
  border-radius: 0.3rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  position: relative;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 1.25rem;
}

.close {
  float: right;
  font-size: 1.5rem;
  font-weight: 700;
  line-height: 1;
  color: #000;
  text-shadow: 0 1px 0 #fff;
  opacity: .5;
  background: none;
  border: none;
  cursor: pointer;
}

.close:hover {
  opacity: .75;
}

.modal-body {
  padding: 20px;
  position: relative;
  flex: 1 1 auto;
  max-height: 60vh;
  overflow-y: auto;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #e9ecef;
  display: flex;
  justify-content: flex-end;
  flex-wrap: wrap;
  gap: 10px;
}

.clause-select-list {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 模态框过渡动画 */
.modal-fade-enter-active, .modal-fade-leave-active {
  transition: opacity 0.3s;
}
.modal-fade-enter, .modal-fade-leave-to {
  opacity: 0;
}

/* AI助手样式 */
.ai-modal {
  max-width: 600px;
}

.ai-header {
  background-color: #f8f9fa;
}

.ai-body {
  padding: 0;
  display: flex;
  flex-direction: column;
  height: 500px;
}

.chat-messages {
  flex-grow: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.message {
  display: flex;
  margin-bottom: 15px;
  max-width: 90%;
}

.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.assistant {
  align-self: flex-start;
}

.avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 10px;
  font-size: 16px;
}

.user .avatar {
  background-color: #007bff;
  color: white;
}

.assistant .avatar {
  background-color: #f8f9fa;
  color: #333;
}

.message-content {
  background-color: #f8f9fa;
  padding: 10px 15px;
  border-radius: 18px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.user .message-content {
  background-color: #007bff;
  color: white;
}

.chat-input {
  display: flex;
  padding: 15px;
  border-top: 1px solid #e9ecef;
}

.chat-input textarea {
  flex-grow: 1;
  border: 1px solid #ced4da;
  border-radius: 4px;
  padding: 10px;
  resize: none;
  margin-right: 10px;
}

.send-btn {
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0 15px;
  cursor: pointer;
}

.send-btn:hover {
  background-color: #0069d9;
}
</style>